package 力扣.堆;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class 吃苹果的最大数目1705 {
    public static void main(String[] args) {
        int[] apples = {3,0,0,0,0,2};
        int[] days = {3,0,0,0,0,2};
        int i = eatenApples(apples, days);
        System.out.println(i);
    }

    /**
     * 优先吃掉快过期的果子（将消耗的过程变为收集的过程，然后选择最大值/最小值）
     * @param apples
     * @param days
     * @return
     */
    public static int eatenApples(int[] apples, int[] days) {
        int ans = 0;
        PriorityQueue<Integer[]> pq = new PriorityQueue<Integer[]>(new Comparator<Integer[]>() {
            @Override
            public int compare(Integer[] o1, Integer[] o2) {
                    return o1[0] - o2[0];//根据坏掉的时间：小根堆
            }
        });
        for (int i = 0; i < apples.length || !pq.isEmpty(); i++) {
            if (i < apples.length){
                int expire = days[i] - 1 + i;//记录果子在哪一天会坏掉
                int num = apples[i];
                pq.offer(new Integer[]{expire,num});
            }
            while (!pq.isEmpty() && pq.peek()[0] < i){//果子过期
                 pq.poll();
            }
            while (!pq.isEmpty() && pq.peek()[1] == 0){//果子数量为零的情况
                pq.poll();
            }
            if (!pq.isEmpty()){//吃果子
                --pq.peek()[1];
                ans++;
            }
        }
        return ans;
    }
}
